﻿using ASmile.Extend;
using System;

namespace ASmile.Com
{
    public class LoginUser
    {
        /// <summary>
        /// 当前用户Id
        /// </summary>
        public string UserId { set; get; }
        /// <summary>
        /// 用户名
        /// </summary>
        public string UserName { set; get; }
        /// <summary>
        /// 角色
        /// </summary>
        public string RoleId { set; get; }
        /// <summary>
        /// 角色名称
        /// </summary>
        public string RoleName { set; get; }
        /// <summary>
        /// 科室Id
        /// </summary>
        public string DeptId { set; get; }
        /// <summary>
        /// 科室名称
        /// </summary>
        public string DeptName { set; get; }
        /// <summary>
        /// 是否管理员
        /// </summary>
        public bool IsManager { set; get; }
        /// <summary>
        /// 客户端Id,用于区分客户端
        /// </summary>
        public string ClientId { set; get; }
#if !NET40

        /// <summary>
        /// 过期时长
        /// </summary>
        public TimeSpan Expires { set; get; }
        /// <summary>
        /// 在指定该时间之后有效
        /// </summary>
        public DateTime? NotBefore { set; get; }
        /// <summary>
        /// 过期时间(创建token时赋值)
        /// </summary>
        public DateTime ExpiresTime { get; set; }        
        /// <summary>
        /// 客户端IP
        /// </summary>
        public string ClientIP { set; get; }
        /// <summary>
        /// 创建一个新token,并赋值 ExpiresTime
        /// </summary>
        public override string ToString()
        {
            string[] arr = new[] {
                UserId,
                UserName,
                RoleId,
                DeptId,
                DeptName,
                Expires.TotalMinutes.ToString("0"),
                NotBefore?.ToTimestamp().ToString(),
                ExpiresTime.ToTimestamp().ToString(),
                IsManager.ToString(),
                ClientId,
                ClientIP
            };
            return string.Join("\t", arr);
        }

        public static LoginUser FromString(string str)
        {
            LoginUser user = new LoginUser();
            int i = 0;
            var arr = str.Split('\t');
            user.UserId = arr[i++];
            user.UserName = arr[i++];
            user.RoleId = arr[i++];
            user.DeptId = arr[i++];
            user.DeptName = arr[i++];
            user.Expires = TimeSpan.FromMinutes(int.Parse(arr[i++]));
            if (!arr[i++].IsEmpty())
            {
                user.NotBefore = long.Parse(arr[i]).ToTime();
            }
            user.ExpiresTime = long.Parse(arr[i++]).ToTime();
            user.IsManager = bool.Parse(arr[i++]);
            user.ClientId = arr[i++];
            if (arr.Length > i + 1) user.ClientIP = arr[i++];
            return user;
        }
#endif
    }
}
